cc.Class({
    extends: cc.Component,
  
    properties: {
      speed: 10,
      bulletPre:cc.Prefab
    },

    start() {
      this.viewWidth = cc.view.getVisibleSize().width;
      this.viewHeight = cc.view.getVisibleSize().height;
      if (DataMangrt.bullet_model && DataMangrt.enemyArray.length) {
        let m = DataMangrt.enemyArray.length;
        let n = Math.floor(Math.random() * m);
        this.target = DataMangrt.enemyArray[n];
      }
    },
    Genzong() {
      var targetPoint = this.target.position;
      var point = cc.v2(this.node.x, this.node.y);
      var delta = targetPoint.sub(point);
      this.distance = point.sub(targetPoint).mag();
      var x2 = point.x + (this.speed * delta.x) / this.distance;
      var y2 = point.y + (this.speed * delta.y) / this.distance;
     
      var newPosition = cc.v2(x2, y2);
      var x1 = point.x;//改变子弹角度
      var y1 = point.y;
      var deltaRotation = 90 -Math.atan2(y2 - y1, x2 - x1) * 180 /Math.PI;
      this.node.angle=-deltaRotation;
     
      this.node.setPosition(newPosition);
    },
   
    onCollisionEnter: function (other, self) {
      if (other.tag == 1) {
        var enemy = other.node.getComponent("enemy");//敌人1
      } else if (other.tag == 2) {
        var enemy = other.node.getComponent("enemy2");//敌人2
      } else if (other.tag == 3) {
        var enemy = other.node.getComponent("enemy3");//敌人3
      }
      if (enemy && enemy.isDie == false) {
        enemy.hit(5);
        // this.bulletPre.data.getComponent("bullet").checkNUmber();

      }
      this.onDestroy();
    },
    onDestroy:function(){
      if (this.node) {
        this.node.destroy();
      }
    },
    update(dt) {
      game.enemyArrayPush();
        if (this.node) {
          let end_pos = this.node.getPosition();
          if(end_pos.x<-this.viewWidth/2 || end_pos.x>this.viewWidth/2 || (end_pos.y<-this.viewHeight/2) || (end_pos.y>this.viewHeight/2)){   //屏幕检测
            this.onDestroy();
            console.log('销毁出屏幕的跟踪子弹');
            
          }
        }
      if (DataMangrt.enemyArray.length) {
        for (let i = 0; i <  DataMangrt.enemyArray.length; i++) {//检测敌人数组
          if(DataMangrt.enemyArray[i]._parent==null) {
              DataMangrt.enemyArray = DataMangrt.enemyArray.filter(element => element!==DataMangrt.enemyArray[i])
          }
        }
        if (this.target&&this.node) {
          this.Genzong();
        }
        else{
          let m = DataMangrt.enemyArray.length;
          let n = Math.floor(Math.random() * m);
          this.target = DataMangrt.enemyArray[n];
          this.Genzong();
          console.log('无目标');
        }
      }
      else{
        this.onDestroy()
        console.log('没有敌人，销毁子弹');
      }
    },
  });
  